import { RedisService } from '@/redis/redis.service'
import { GetAccessTokenDto } from '@/wxapp/wx-api/dto/get-access-token.dto'
import { Injectable, Logger } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Cron, CronExpression, Timeout } from '@nestjs/schedule'
import axios from 'axios'

@Injectable()
export class TimeWorkerService {
  constructor(
    private readonly config: ConfigService,
    private readonly redisService: RedisService,
    private logger: Logger,
  ) {
    this.logger = new Logger(TimeWorkerService.name)
  }

  //每2小时执行一次
  @Cron(CronExpression.EVERY_2_HOURS)
  async resetAcessToken() {
    await this.setAccessToken()
    this.logger.verbose('获取一次access_token')
  }

  @Timeout(10000)
  async firstAcessToken() {
    await this.setAccessToken()
    this.logger.verbose('获取一次access_token')
  }

  async setAccessToken() {
    let query: GetAccessTokenDto = {
      appid: this.config.get('APPID'),
      secret: this.config.get('APP_SECRET'),
      grant_type: this.config.get('GRANT_TYPE'),
    }
    const res = await this.getAccessToken(query)
    if (res.access_token) {
      await this.redisService.set('access_token', res.access_token, res.expires_in)
    }
  }

  async getAccessToken(query: GetAccessTokenDto) {
    const res = await axios.get(
      `https://api.weixin.qq.com/cgi-bin/token?grant_type=${query.grant_type}&appid=${query.appid}&secret=${query.secret}`,
    )
    return res.data
  }
}
